package com.mibotiquin.misfarmacos;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.mibotiquin.map.Pharmacies;

public class ProspectoData {
	private String prospec;
	private  String server;
	
	public ProspectoData(String server){
		this.server = server;
	}
	
	/**process information received from the server
	 * 
	 * @return List<Pharmacies>
	 */
	public String run(){
		String dateServer = readServerInformation();
		if(dateServer != null){
			try{
				JSONObject jsonObject = new JSONObject(dateServer);
				int jsonStatus = Integer.parseInt(jsonObject.getString("success"));
				if (jsonStatus == 1){
					prospec = jsonObject.getString("texto");
					
				}
			}catch (Exception e){	
				e.printStackTrace();
			}
		}
		return prospec;
	}
	
	/**make the request
	 * 
	 * @return String
	 */
	private String readServerInformation(){
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(server);
		try{
			HttpResponse reply = client.execute(httpGet);
			StatusLine statusLine = reply.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if(statusCode == 200){
				HttpEntity entity = reply.getEntity();
				InputStream contenido = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(contenido));
				String line;
				while ((line=reader.readLine()) != null){
					builder.append(line);
				}
			}else{	
			}
		}catch (ClientProtocolException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return builder.toString();
	}
	
}
